package com.zbw.weightlibrary.Connector;

import com.zbw.weightlibrary.Util.ConversionUtil;
import com.zbw.weightlibrary.Util.ThreadPoolManager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * 作者 ：Wesley
 * 时间 ：2023-07-08 11:00
 * 这个类是干嘛的？：BaseControllmplRongDa
 */
public abstract class BaseControllmplRongDa implements IBleControl{

   private final DecimalFormat decimalFormat = new DecimalFormat("0.000");
   //添加公共参数、功能等
   private final IinfoCallback mCallback;
   protected boolean ReadWeight;//是否读取重量
   protected ArrayList<byte[]> mRecvData;
   protected int ValueSize;

   public BaseControllmplRongDa(IinfoCallback callback) {
      mCallback = callback;
   }

   protected void ReadWeight(final InputStream inputStream) {
      ReadWeight = true;
      mRecvData = new ArrayList<>();
      ValueSize = 0;
      ThreadPoolManager.getInstance().executeTask(new Runnable() {
         @Override
         public void run() {
            try {
               byte[] data = new byte[128];
               int size;
               while (inputStream != null && ReadWeight) {
                  if (inputStream.available() > 0) {
                     size = inputStream.read(data);
                     if (size > 0) {
                        ByteBuffer bb = ByteBuffer.allocate(size);
                        bb.put(data, 0, size);
                        postOnReceived(bb.array());
                     } else {
                        break;
                     }
                  } else {
                     Thread.sleep(100);
                  }
               }
            } catch (Exception e) {
               e.printStackTrace();
               mCallback.onGetWeight("获取重量失败！" + e.getMessage(),false);
            }
         }
      });
   }

   protected void postOnReceived(byte[] data) {
      synchronized (mRecvData) {
         mRecvData.add(data);
         while (countByteArrayList(mRecvData) > 1024)
            mRecvData.remove(0);

         byte[] bytes = null;
         synchronized (mRecvData) {
            for (byte[] d : mRecvData) {
               bytes = d;
            }
         }
         if (bytes != null) {
            CutOutString(bytes);
         }
      }
   }

   /**
    * @param value 接收到的byte数组
    * 麟罗电子秤解析
    */
   protected void CutOutString(byte[] value) {
      //第一步,byte数组转16进制字符串
      String hxStr = ConversionUtil.byte2Hex(value).trim();
      //第二步,用split()方法进行切割，得到对应的数组长度
      String[] data = hxStr.split(" ");
      //容大返回数据固定 19位 第一位固定为 02
      if(data.length == 19 && "02".equals(data[0])) {
         String symbol = "2d".equals(data[1])?"-":"";
         String netWeight = getStringByIndex(2,7,data);
         netWeight = String.format("%s%s", symbol, ConversionUtil.hexStr2Str(netWeight).trim());
         Double w = Double.parseDouble(netWeight) * 0.001;
         netWeight = decimalFormat.format(w);
         boolean sta = "13".equals(data[8])||"1b".equals(data[8])||"3b".equals(data[8])||"33".equals(data[8]);
         if(mCallback!=null){
            mCallback.onGetWeight(netWeight, sta);
         }
      }
   }

   /**
    * 拼接对应范围内的数组
    * @param start 开始位置
    * @param end 结束位置
    * @param data 目标数组
    * @return 指定范围拼接的字符串
    */
   private String getStringByIndex(int start,int end,String[] data){
      StringBuilder checkStr = new StringBuilder();
      //检验内容是除去数据头尾和校验字符
      for (int i=start;i<end;i++){
         checkStr.append(data[i]);
      }
      return checkStr.toString();
   }

   private int countByteArrayList(ArrayList<byte[]> data) {
      int size = 0;
      for (byte[] d : data)
         size += d.length;
      return size;
   }

   /**
    * 发送指令
    */
   protected void sendCode(OutputStream os, String code) {
      if (os == null || code.isEmpty()) return;
      try {
         byte[] bytes = ConversionUtil.hexStringToByteArray(code);
         os.write(bytes);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

}
